<script setup lang="js">
    import * as echarts from 'echarts'
    import axios from 'axios';
    import { ref,reactive,onMounted } from 'vue';
    //-导入地图的数据
    import china_geo from '../resource/china.json';


    let options = reactive([]);
    let zoomScale = 1;
    //-省份的匹配（目前服务器返回的省份名称与json数据中的省份名称不匹配）
    function formatCityName(cityName){
        const replacements = {
            "浙江": "浙江省",
            "上海": "上海市",
            "重庆": "重庆市",
            "河北": "河北省",
            "北京": "北京市",
            "天津": "天津省",
            "山西": "山西省",
            "海南": "海南省",
            "内蒙古": "内蒙古自治区",
            "湖北": "湖北省",
            "广西": "广西壮族自治区",
            "湖南": "湖南省",
            "辽宁":"辽宁省",
            "吉林": "吉林省",
            "黑龙江": "黑龙江省",
            "江苏": "江苏省",
            "安徽": "安徽省",
            "福建": "福建省",
            "江西": "江西省",
            "山东": "山东省",
            "湖北": "湖北省",
            "河南": "河南省",
            "广东": "广东省",
            "海南": "海南省",
            "四川":"四川省",
            "甘肃": "甘肃省",
            "青海": "青海省",
            "甘肃": "甘肃省",
            "新疆": "新疆维吾尔自治区",
            "西藏": "西藏自治区",
            "宁夏": "宁夏回族自治区",
            "陕西": "陕西省",
            "云南": "云南省",
            "贵州": "贵州省",
            //-自行添加
        };
        return replacements[cityName] || cityName;
    }
    function handleZoom(delta) {
        // 根据鼠标滚轮方向调整缩放比例
        if (delta > 0) {
            zoomScale *= 1.1;
        } else {
            zoomScale *= 0.9;
        }
        // 限制缩放比例范围，可根据实际情况调整
        if (zoomScale < 0.5) {
            zoomScale = 0.5;
        } else if (zoomScale > 2) {
            zoomScale = 2;
        }
    }
    const chartMap = ref();
    
    //-初始化图表
    function initChart(){
        //初始化echarts实例对象
        const myChart = echarts.init(chartMap.value,'light',{
            height: 800,
            width: 800
        })
        //将地图数据注入到echarts中
        echarts.registerMap('china',china_geo);
        // 图表的配置项
         // 绑定鼠标滚轮事件
          myChart.getDom().addEventListener('mousewheel', function (event) {
              let delta = event.wheelDelta? event.wheelDelta / 100 : -event.detail / 3;
              handleZoom(delta);
              // 应用缩放比例到每层地图的相关参数，实现同步缩放
              updateMapZoom(myChart, zoomScale);
          });
        const option = {
            //-标题
          
            title: {
                text: '双\n一\n流\n学\n校\n全\n国\n分\n布\n可\n视\n化',
                top:'35%',
                left:"0px",
                textStyle: {
                    color: '#fff',
                    fontWeight: 'bold',
                    fontSize: '25px'
                }
            },
           
            //-图例
            tooltip:{
              show:true,
              trigger: 'item',
              formatter: function (params) {
                   
                    const dataArray = myChart.getOption().series[0].data;
                    let tooltipContent = '';
                    let valueNameMap = {};

                    // 构建 valueNameMap 对象（值到名称数组的映射）
                    if (Array.isArray(dataArray)) {
                        for (let i = 0; i < dataArray.length; i++) {
                            const dataItem = dataArray[i];
                            if (dataItem && dataItem.hasOwnProperty('value') && dataItem.hasOwnProperty('name')) {
                                const value = dataItem.value;
                                if (!valueNameMap[value]) {
                                    valueNameMap[value] = [];
                                }
                                valueNameMap[value].push(dataItem.name);
                            } else {
                                console.warn('数据项结构不符合预期，可能影响后续功能', dataItem);
                            }
                        }
                    } 
                    // 根据特定数值构建提示信息内容
                    if (Array.isArray(params.value) && params.value.length > 0) {
                        const paramValue = params.value[0]+','+params.value[1];
                        for (const numValue in valueNameMap) {
                            if (numValue === paramValue) {
                              console.log(valueNameMap);
                                tooltipContent += `该省的双一流大学有：<br>`;
                                const nameArray = valueNameMap[numValue];
                                nameArray.forEach(name => {
                                    tooltipContent += `${name}<br>`;
                                });
                                tooltipContent += `<br>`;
                            }
                        }
                    } else {
                        console.warn('传入的参数不符合预期，无法正确构建提示信息', params);
                    }
                    return tooltipContent;
                }
            },
               
            
            //-数据:地图配置
            
         geo: [
          {
            map: 'china',
            aspectScale: 1,
            zoom: 0.9,
            layoutCenter: ['50%', '65%'],
            layoutSize: '100%',
            show: true,
            roam: false,
            label: {
              show: false, // 各个省市县的名字
              color: '#fff',
            },
            itemStyle: {
              // 每块的样式
              areaColor: {
                type: 'linear',
                x: 1200,
                y: 0,
                x2: 0,
                y2: 0,
                colorStops: [
                  {
                    offset: 0,
                    color: 'rgba(3,27,78,0.75)',
                  },
                  {
                    offset: 1,
                    color: 'rgba(58,149,253,0.75)',
                  },
                ],
                global: true, // 缺省为 false
              },
              borderColor: '#c0f3fb',
              borderWidth: 0.8,
            },
            emphasis: {
              itemStyle: {
                show: false,
                color: '#fff',
                areaColor: 'rgba(0,254,233,0.6)',
              },
              label: {
                show: true,
                color: '#fff',

              },
            },
          },
          
          // 重影
          {
            type: 'map',
            map: 'china',
            zlevel: -1,
            aspectScale: 1,
            zoom: 0.9,
            layoutCenter: ['50%', '66%'],
            layoutSize: '100%',
            roam: false,
            silent: true,
            itemStyle: {
              borderWidth: 1,
              borderColor: 'rgba(58,149,253,0.8)',
              shadowColor: 'rgba(172, 122, 255,0.5)',
              shadowOffsetY: 5,
              shadowBlur: 15,
              areaColor: 'rgba(5,21,35,0.1)',
            },
          },
          {
            type: 'map',
            map: 'china',
            zlevel: -2,
            aspectScale: 1,
            zoom: 0.9,
            layoutCenter: ['50%', '67%'],
            layoutSize: '100%',
            roam: false,
            silent: true,
            itemStyle: {
              borderWidth: 1,
              borderColor: 'rgba(58,149,253,0.6)',
              shadowColor: 'rgba(65, 214, 255,0.6)',
              shadowOffsetY: 5,
              shadowBlur: 15,
              areaColor: 'rgba(5,21,35,0.1)',
            },
          },
          {
            type: 'map',
            map: 'china',
            zlevel: -3,
            aspectScale: 1,
            zoom: 0.9,
            layoutCenter: ['50%', '68%'],
            layoutSize: '100%',
            roam: false,
            silent: true,
            itemStyle: {
              borderWidth: 1,
              borderColor: 'rgba(58,149,253,0.4)',
              shadowColor: 'rgba(29, 111, 165,1)',
              shadowOffsetY: 15,
              shadowBlur: 10,
              areaColor: 'rgba(5,21,35,0.1)',
            },
          },
          {
            type: 'map',
            map: 'china',
            zlevel: -4,
            aspectScale: 1,
            zoom: 0.9,
            layoutCenter: ['50%', '69%'],
            layoutSize: '100%',
            roam: false,
            silent: true,
            itemStyle: {
              borderWidth: 5,
              borderColor: 'rgba(5,9,57,0.8)',
              shadowColor: 'rgba(29, 111, 165,0.8)',
              shadowOffsetY: 15,
              shadowBlur: 10,
              areaColor: 'rgba(5,21,35,0.1)',
            },
          },
        ],
 
            //-数据的效果
            series: [
                {
                    // name:"该省双一流大学",
                  
                    geoIndex: 0,
                    //-涟漪特效动画
                    color:"#14C7F2",
                    type: 'effectScatter',
                    showEffectOn: 'render',
                    data:  [],
                    coordinateSystem: 'geo',
                    //-特效设置
                    rippleEffect: {
                      period: 5,
                      number:3,
                      scale:5,
                      brushType: 'stroke',
                    }
                },
                
            ]
        },
        
         //-动态赋值：
         provinceData = reactive([]) 
        
        for(let index=0;index<options.length;index++){
                        //console.log(data[index].province)
                        //-获取数据库中对应的省份名称
                        let province = options[index].province;
                        //-:获取省份坐标
                        let obj = china_geo.features.find(item=> item.properties.name === formatCityName(province))
                        //console.log(obj)
                        //-如果没有省份名称，则出现空的现象
                        if(obj!=undefined){
                            //console.log(options[index].citySchool+'---'+obj.properties.center)
                            let provinceObj = {
                              
                                name: options[index].citySchool,
                                value: obj.properties.center
                            }
                            //console.log(obj.properties.center)
                            provinceData.push(provinceObj);
                        }

        }
        option.series[0].data = provinceData;
        //console.log(provinceData )
        // 将图表与数据项进行绑定
        function updateMapZoom(myChart, zoomScale) {
          const option = myChart.getOption();
          option.geo.forEach((geoConfig) => {
              if (geoConfig.zoom) {
                  geoConfig.zoom *= zoomScale;
              }
          });
          // 更新effectScatter特效的缩放比例
          const seriesOption = option.series;
          if (seriesOption && seriesOption.length > 0 && seriesOption[0].type === 'effectScatter') {
              seriesOption[0].rippleEffect.scale *= zoomScale;
          }
          myChart.setOption(option);
      }
        myChart.setOption(option);
      }
      //-：获取后端中返回的省份信息
    function getData(){
        axios.get('/Pro-Postgraduate/queryAllDFC')
            .then((response)=>{
                //console.log(response.data)
                if(response.data.code==200){
                  let data = response.data.data;
                  options = data;
                  //=:初始化图表
                  initChart();
                  //console.log(data)
                }
            })
    }
    onMounted(()=>{
      getData();
      //initChart();
    })

</script>
<template>
    <div ref="chartMap" ></div>
    
</template>
<style lang="css" scoped>
  *{
    position: relative;
    left: 3%;
    right:0%;
    bottom: 43%;
  }
</style>
